﻿package no.doomsday.aronning.engines.verlets.utils 
{
	import no.doomsday.aronning.engines.verlets.Verlet;
	
	/**
	 * ...
	 * @author Andreas Rønning
	 */
	public class CollissionTests 
	{
		
		public function CollissionTests() 
		{
			
		}
		
		public static function getIntersectionPoint(a:Verlet, b:Verlet, c:Verlet, d:Verlet):Verlet {
			var tc1:Number, tc2:Number, sc1:Number, sc2:Number, con1:Number, con2:Number, det:Number, con:Number, s:Number;
			tc1 = b.x - a.x;
			tc2 = b.y - a.y;
			sc1 = c.x - d.x;
			sc2 = c.y - d.y;
			con1 = c.x - a.x;
			con2 = c.y - a.y;
			det = (tc2 * sc1 - tc1 * sc2);
			if (det == 0) throw new Error("No unique solution (probably parallel vectors)");
			con = tc2 * con1 - tc1 * con2;
			s = con / det;
			var vec:Verlet = new Verlet(c.x + s * (d.x - c.x), c.y + s * (d.y - c.y));
			return vec;
		}
		public static function getIntersectionTime(p1:Verlet, v1:Verlet, p2:Verlet, v2:Verlet):Number {
			var tc1:Number = v1.x;
			var tc2:Number = v1.y;
			var sc1:Number = v2.x;
			var sc2:Number	= v2.y;
			var con1:Number = p2.x - p1.x;
			var con2:Number = p2.y - p1.y;
			var det:Number = tc2 * sc1 - tc1 * sc2;
			if (det == 0) throw new Error("No unique solution (probably parallel vectors)");
			var con:Number = sc1 * con2 - sc2 * con1;
			var t:Number = con / det;
			return t;
		}
		
		public static function getIntersectionPoint2(a:Verlet, b:Verlet, c:Verlet, d:Verlet):Verlet {
			var p:Number = getIntersectionPosition(a, b, c, d);
			if (p < 0 || p > 1) throw new Error("No collission");
			var v:Verlet = new Verlet(a.x + (b.x-a.x)*p, a.y + (b.y-a.y)*p);
			return v;
		}
		
		public static function getIntersectionPosition(a:Verlet, b:Verlet, c:Verlet, d:Verlet):Number{
			var tc1:Number, tc2:Number, sc1:Number, sc2:Number, con1:Number, con2:Number, det:Number, con:Number, s:Number,t:Number;
			tc1 = b.x - a.x;
			tc2 = b.y - a.y;
			sc1 = c.x - d.x;
			sc2 = c.y - d.y;
			con1 = c.x - a.x;
			con2 = c.y - a.y;
			det = (tc2 * sc1 - tc1 * sc2);
			if (det == 0) throw new Error("No unique solution (probably parallel vectors)");
			con = tc2 * con1 - tc1 * con2;
			s = con / det;
			if (s<0||s>1) return -1;
			if (tc1 != 0) {
				t = (con2 - s * sc2) / tc2;
			}else {
				t = (con2 - s * sc2) / tc2;
			}
			if (t<0||t>1) return -1;
			if (isNaN(t)) return -1;
			return t;
		}
		
	}
	
}